from rest_framework import serializers
from django_redis import get_redis_connection
class SmsCodeSerializer(serializers.Serializer):
    text = serializers.CharField(min_length=4, max_length=4, label="图片验证码")
    image_code_id = serializers.UUIDField(label="验证码编号")

    def validate(self, attrs):
        text = attrs['text']

        image_code_id = attrs['image_code_id']

        redis_conn = get_redis_connection('code')
        redis_text = redis_conn.get('image_code_%s' % image_code_id)

        if not redis_text:
            raise serializers.ValidationError('验证码已过期')

        if text.lower() != redis_text.decode().lower():
            raise serializers.ValidationError('验证码不正确')

        return attrs